import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:base_lib/index.dart';
import 'package:doctor_examine_lib/hospital_list/hospital_list_entity.dart'
    as HospitalBean;
import 'package:doctor_examine_lib/repository/https.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorLoginBean;
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class HospitalListBloc extends BaseBloc {
  DoctorLoginBean.DoctorUser _doctorInfo;
  var _dataSource = List<HospitalBean.Datum>();
  BehaviorSubject<List<HospitalBean.Datum>> dataSourceSubject =
      BehaviorSubject();

  int _selectedIndex = 0;
  BehaviorSubject<int> selectedIndexSubject = BehaviorSubject();

  @override
  void initState() async {
    super.initState();

    var doctorInfo = await UserInfoCache.getInstance().get();
    _doctorInfo = doctorInfo;
  }

  // 网路请求--获取医院列表
  void fetchHospitalDoctors(VoidCallback success, VoidCallback fail) async {
    var queryParams = Map<String, dynamic>()
      ..["doctorID"] = _doctorInfo.keyID
      ..["latitude"] = "30.53972816467285"
      ..["longitude"] = "104.05217742919922";
    var result = await DoctorExamineHttp.getDoctorHospital(queryParams);
    if (result.isSuccess) {
      _dataSource = result.data;
      dataSourceSubject.add(_dataSource);
      success();
    } else {
      fail();
    }
  }

  // 操作--选择医院
  void selectedItem(index) {
    _selectedIndex = index;
    selectedIndexSubject.add(_selectedIndex);
  }

  // 操作--确认选择医院
  void confirmSelectedHospital(context) {
    if (ObjectUtil.isEmpty(_dataSource[_selectedIndex])) {
      ToastUtil.warning("请选择医院");
      return;
    }
    Routers.pop(context,
        Parameters()..putObj('hospitalInfo', _dataSource[_selectedIndex]));
  }

  @override
  void dispose() {
    dataSourceSubject?.close();
    selectedIndexSubject?.close();
  }
}
